# -*- coding: utf-8 -*-
# @Time    : 2023/7/11 0011 10:30
# @Author  : zcj
# @File    : ssh_linux.py
# @Software : PyCharm
# coding=gbk
import zipfile

import time

import paramiko
import os

from common.util import report_path, host, user, passwd, zip_file_path


def runSshCmd(cmd, *userinof):
    ip = userinof[0]
    name = userinof[1]
    pwd = userinof[2]
    transport = paramiko.Transport(ip, 22)
    # 建立连接
    transport.connect(username=name, password=pwd)
    # 将sshclient的对象的transport指定为以上的transport
    ssh = paramiko.SSHClient()
    ssh._transport = transport
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    # 执行命令
    stdin, stdout, stderr = ssh.exec_command(cmd)
    # 获取命令结果
    res, err = stdout.read(), stderr.read()
    result = res if res else err
    print(result.decode())
    # 关闭连接
    ssh.close()
    transport.close()


# 上传
def putfile(inpath, outpath, *userinof):
    ip = userinof[0]
    name = userinof[1]
    pwd = userinof[2]
    transport = paramiko.Transport(ip, 22)
    # 建立连接
    transport.connect(username=name, password=pwd)
    # 将sshclient的对象的transport指定为以上的transport
    # ssh = paramiko.SSHClient()
    sftp = paramiko.SFTPClient.from_transport(transport)
    # LocalFile.txt 上传至服务器 /home/fishman/test/remote.txt
    sftp.put(inpath, outpath)
    # stdin, stdout, stderr = ssh.exec_command('')
    transport.close()


# 下载
def getfile(inpath, outpath, *userinof):
    ip = userinof[0]
    name = userinof[1]
    pwd = userinof[2]
    transport = paramiko.Transport(ip, 22)
    # 建立连接
    transport.connect(username=name, password=pwd)
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    sftp = paramiko.SFTPClient.from_transport(transport)
    # 将LinuxFile.txt 下载到本地 fromlinux.txt文件中
    sftp.get(outpath, inpath)
    transport.close()


def newcrontab(crontabstr, ip, name, pwd):
    crontabstr = """echo "0 */1 * * * python  /home/kt/getPm/CityDataSpider.py"  >> /opt/zcj/ """
    runSshCmd(crontabstr, ip, name, pwd)


# def linDeploy(ip,name,pwd):
# def putfile(inpath,outpath,*userinof)
#     crontabstr=""
#     runSshCmd(crontabstr,ip.name,pwd)


def get_dir_file(path):
    fpath = os.chdir(path)

    file_names = os.listdir(fpath)  # 获取指定目录下的 所有文件名称 排序方式是从大到小
    return file_names


def zip_file(src_dir):
    zip_name = src_dir + '.zip'
    z = zipfile.ZipFile(zip_name, 'w', zipfile.ZIP_DEFLATED)
    for dirpath, dirnames, filenames in os.walk(src_dir):
        fpath = dirpath.replace(src_dir, '')
        fpath = fpath and fpath + os.sep or ''
        for filename in filenames:
            z.write(os.path.join(dirpath, filename), fpath + filename)
            print('==压缩成功==')
    z.close()


# 以下数据是写死的 后续需要提取 参数化
def send_linux():
    zip_file(report_path + "/allure-report")
    t = time.strftime('%Y-%m-%d_%H-%M')
    linux_file = f"report_{t}"
    print(linux_file)
    print(t)
    try:
        putfile(rf"{report_path}\allure-report.zip", f"/opt/allure-report.zip",
                host, user, passwd)
        print(f"本地文件上传成功...上传至Linux")
        # 执行shell脚本
        runSshCmd(f"mkdir -p /opt/allure_report/{linux_file} ", host, user, passwd)
        runSshCmd(f"unzip -d /opt/allure_report/{linux_file} /opt/allure-report.zip && rm /opt/allure-report.zip ",
                  host, user, passwd)
        runSshCmd(f"mv /opt/allure_report/{linux_file} {zip_file_path} ", host, user, passwd)
        return "http://192.167.6.185:8090/" + linux_file
        # print("旧包已经删除...新包放置成功")
    except Exception as e:
        print(e)


if __name__ == '__main__':
    send_linux()
